package com.xxbb.jdbc.db;

import java.sql.*;

public class DBUtil {
    private static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/javadb";
    private static final String USER = "root";
    private static final String PASSWORD = "927114";

    //1、加载驱动
    static {
        try {
            Class.forName(DRIVER_NAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //2、创建连接
    public static Connection connection() {
        try {
            return DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    //3.修改
    public static Integer update(String sql,Object... objects){

        try {
            PreparedStatement preparedStatement = connection().prepareStatement(sql);
            // 判断sql是否存在？占位符
            if (objects != null) {
                for (int i = 0; i < objects.length; i++) {
                    try {
                        preparedStatement.setObject((i + 1), objects[i]);
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
    //4.查询
    public static ResultSet query(String sql,Object... objects){
        try {
           PreparedStatement preparedStatement = connection().prepareStatement(sql);
            // 判断sql是否存在？占位符
            if (objects != null) {
                for (int i = 0; i < objects.length; i++) {
                    try {
                        preparedStatement.setObject((i + 1), objects[i]);
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //5、关闭连接,释放资源
    public static void close(ResultSet resultset, PreparedStatement preparedStatement, Connection connection) {

        try {
            if (resultset != null) {
                resultset.close();
            }
            if (connection != null) {
                connection.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
